import torch
from torch import nn
from d2l import torch as d2l
from torch.nn import functional as f

class Residual(nn.Module):
    def __init__(self,input_channels,output_channels,use1x1conv=False,stride=1):
        super.__init__()
        self.conv1 = nn.Conv2d(
            input_channels,output_channels,kernel_size=3,padding=1,stride=stride)
        self.conv2 = nn.Conv2d(
            output_channels,output_channels,kernel_size=3,padding=1)
        if use1x1conv:
            self.conv3 = nn.Conv2d(
                input_channels,output_channels,kernel_size=1,stride=stride)
        else:
            self.conv3 = None
        self.bn1 = nn.BatchNorm2d(output_channels)
        self.bn2 = nn.BatchNorm2d(output_channels)
        self.relu = nn.ReLU(inplace=None)
    
    def forward(self,X):
        Y = f.relu(self.bn1(self.conv1(X)))
        Y = self.bn2(self.conv2(Y))
        if self.conv3:
            X = self.conv3(X)
        Y += X
        return f.relu(Y)
    
b1 = nn.Sequential(
    nn.Conv2d(1,64,kernel_size=7,stride=2,padding=1),
    nn.BatchNorm2d(64),nn.ReLU(),
    nn.MaxPool2d(kernel_size=3,stride=2,padding=1)
)

def res_block(input_channels,output_channels,num_residuals,first_block=False):
    blocks = []
    for i in range(num_residuals):
        if i == 0 and not first_block:
            blocks.append(Residual(input_channels,output_channels,use1x1conv=False,stride=2))
        else:
            blocks.append(Residual(output_channels,output_channels))

b2 = nn.Sequential(*res_block(64,64,2,first_block=True))
b3 = nn.Sequential(*res_block(64,128,2))
b4 = nn.Sequential(*res_block(128,256,2))
b5 = nn.Sequential(*res_block(256,512,2))
net = nn.Sequential(b1,b2,b3,b4,b5,
                    nn.AdaptiveAvgPool2d((1,1)),nn.Flatten(),nn.Linear(512,10))

    
